layui.define(["element", "jquery"], function (exports) {
    var element = layui.element,
        $ = layui.$;

    var TAB_FILTER = "multiadminTab", 
        TAB_HEADER = '#multi_tab_admin_tab_header'
        TAB_HEADERS = TAB_HEADER + '>li', 
        TAB_BODY = '#multi_tab_admin_tab_body';
    
    var mTab = {
        render: function() {
            mTab.listen()
        },
        listen: function() {
            /**
             * tab事件
             */
            $('body').on('click', '*[lay-tab-event]', function() {
                var othis = $(this),
                    attrEvent = othis.attr('lay-tab-event');
                mTab.events[attrEvent] && mTab.events[attrEvent].call(this, othis);
            });
            /**
             * 打开菜单
             */
            $('body').on('click', '*[lay-href]', function() {
                var othis = $(this),
                    attrEvent = othis.attr('lay-href'),
                    title = othis.attr('lay-title') || othis.attr('lay-text') || othis.children('span').text() || othis.text(),
                    locale = othis.attr('locale-html') || othis.find('[locale-html]').first().attr('locale-html')
                    target = othis.attr('lay-target') || '_self';
                mTab.openTab(attrEvent, title, target, locale);
            });
            /**
             * 监听消息
             */
            receiveMessage(mTab.dealWithMessage)
        },
        openTab: function(url, title, target, locale, tabId, disableClose = false,
            tabsHeaderSelector = TAB_HEADERS, filterTabSelector = TAB_FILTER) {
            if (!url) {
                layer.msg('地址为空!')
                return
            }
            if (target === '_blank') {
                window.open(url, target)
                return
            }
            title = title || '新标签页'
            target = target || '_self'
            tabId = tabId || url
            var matchTo
                , tabs = $(tabsHeaderSelector)
                , path = url.replace(/(^http(s*):)|(\?[\s\S]*$)/g, '');
            tabs.each(function(i) {
                var li = $(this),
                    layid = li.attr('lay-id');
                if (layid === tabId) {
                    matchTo = true
                }
            })
            if (!matchTo) {
                var newURL = url;
                if (setter.urlAddToken) {
                    newURL += (url.indexOf('?') > -1 ? '&' : '?') + 'token=' + getToken();
                }
                element.tabAdd(filterTabSelector, {
                    title: [
                        '<span class="tab-pre-icon"></span>', 
                        '<span locale-html="' + locale + '"' + (disableClose? 'class="disable-close"': '') + '>' + title + '</span>'].join(''),
                    content: '<iframe src="' + newURL + '" class="multi-tab-iframe"></iframe>',
                    id: tabId,
                    attr: path
                });
            }
            element.tabChange(filterTabSelector, tabId);
        },
        dispatchMessage: function(type, body) {
            var topLayui = parent === self ? layui : top.layui
            topLayui.$(TAB_BODY).find('iframe').each(function (index, othis) {
                othis.contentWindow.postMessage({type: type, value: body}, '*')
            })
        },
        dealWithMessage: function(event) {
            var data = event.data || {}
            if (data.type) {
                switch(data.type) {
                    case 'closeTab':
                        if (data.data) {
                            mTab.events[data.data] && mTab.events[data.data].call(this);
                        }
                        break;
                    case 'openTab':
                        var d = data.data || {}
                        mTab.openTab(d.url, d.title, d.target)
                        break;
                    default:
                        break;
                }
            }
        },
        events: {
            closeCurrentTab: function() {
                var othis = $(TAB_HEADERS + '.layui-this'),
                    tabId = othis.attr('lay-id');
                if (othis.find('.disable-close').length < 1) {
                    mTab.events.closeTab(tabId);
                }
            },
            closeOtherTab: function() {
                var othis = $(TAB_HEADERS + ':not(.layui-this)')
                othis.each(function() {
                    if($(this).find('.disable-close').length < 1) {
                        mTab.events.closeTab($(this).attr('lay-id'));
                    }
                })
            },
            closeAllTab: function() {
                var othis = $(TAB_HEADERS)
                othis.each(function() {
                    if($(this).find('.disable-close').length < 1) {
                        mTab.events.closeTab($(this).attr('lay-id'));
                    }
                })
            },
            closeTab: function(tabId, tabFilter = TAB_FILTER) {
                if (tabId) {
                    element.tabDelete(tabFilter, tabId)
                }
            },
            rollLeft: function() {
                mTab.events.rollPage('left')
            },
            rollRight: function() {
                mTab.events.rollPage('right')
            },
            rollPosition: function() {
                var $tabHeader = $(TAB_HEADER);
                var autoLeft = 0;
                $tabHeader.children('li').each(function() {
                    if ($(this).hasClass('layui-this')) {
                        return false;
                    } else {
                        autoLeft += $(this).outerWidth();
                    }
                });
                $tabHeader.animate({
                    scrollLeft: autoLeft - $tabHeader.width() / 3
                }, 200);
            },
            rollPage: function (direction) {
                var $tabHeader = $(TAB_HEADER);
                var left = $tabHeader.scrollLeft();
                if ('left' === direction) {
                    $tabHeader.animate({
                        scrollLeft: left - 450
                    }, 200);
                } else {
                    $tabHeader.animate({
                        scrollLeft: left + 450
                    }, 200);
                }
            }
        }
    };

    exports('mTab', mTab)
});